//
//  OAuthViewController.swift
//  WBDemo
//
//  Created by Jin on 20/04/2018.
//  Copyright © 2018 com.baidu.123. All rights reserved.
//

import UIKit
import WebKit

class OAuthViewController: UIViewController {

    @IBOutlet var webView: WKWebView!
    
    // MARK: - 视图生命周期
    override func viewDidLoad() {
        super.viewDidLoad()

        webView.uiDelegate = self
        webView.navigationDelegate = self
        
        loadPage()
    }


    // MARK: - 内部控制方法
    private func loadPage(){
        let str = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_Redirect_URI)"
        guard let url = URL(string: str) else {
            return
        }
        
        webView.load(URLRequest(url: url))
    }
    
    @IBAction func leftBtnClick(sender:UIBarButtonItem){
        dismiss(animated: true, completion: nil)
    }
    
    @IBAction func rightBtnClick(sender:UIBarButtonItem){
        let js = "document.getElementById('userId').value = '56284720@qq.com';" + "document.getElementById('passwd').value = '495243075q';"
        webView.evaluateJavaScript(js, completionHandler: nil)
    }
}


extension OAuthViewController:WKUIDelegate{
    // 创建一个新的WebView
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        JLog(message: "WKUIDelegate + 创建一个新的WebView")
        return WKWebView()
    }
    
    // 输入框
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        JLog(message: "WKUIDelegate + 输入框")
        completionHandler("http")
    }

    // 确认框
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        JLog(message: "WKUIDelegate + 确认框")
        completionHandler(true);
    }

    // 警告框
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        JLog(message: "WKUIDelegate + 警告框")
        completionHandler()
    }
    
}


extension OAuthViewController:WKNavigationDelegate{
    
    /// 1 在发送请求之前，决定是否跳转
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        JLog(message: "1 在发送请求之前，决定是否跳转")
        decisionHandler(WKNavigationActionPolicy.allow)
    }
    /// 2 页面开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        JLog(message: "2 页面开始加载")
    }
    /// 3 开始获取到网页内容时返回
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        JLog(message: "3 开始获取到网页内容时返回")
    }
    /// 4 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        JLog(message: "4 页面加载完成之后调用")
    }
    /// 5 页面加载失败时调用
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        JLog(message: "页面加载失败时调用")
    }
    // 6 接收到服务器跳转请求之后调用
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        JLog(message: "6 接收到服务器跳转请求之后调用")
    }
    // 7 在收到响应后，决定是否跳转
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        JLog(message: "7 在收到响应后，决定是否跳转")
        JLog(message: navigationResponse.response.url?.absoluteString)
        
        //判断是否是授权回调地址,如果不是就继续跳转
        guard let urlStr = navigationResponse.response.url?.absoluteString, urlStr.hasPrefix(WB_Redirect_URI) else {
            decisionHandler(WKNavigationResponsePolicy.allow)
            return
        }
        
        //判断是否授权成功
        let code = "code="
        guard urlStr.contains(code) else {
            JLog(message: "error_uri")
            decisionHandler(WKNavigationResponsePolicy.cancel)
            return
        }
        
        //授权成功
        if let temp = navigationResponse.response.url?.query {
            let codeStr = temp.suffix(from: code.endIndex)
            JLog(message: codeStr)
            
            //利用requestToken 换取 accessToken
            loadAccessToken(codeStr: String(codeStr))
        }
        
        
        //允许跳转
        //decisionHandler(WKNavigationResponsePolicy.allow)
        //不允许跳转
        decisionHandler(WKNavigationResponsePolicy.cancel)
    }
    
    //获取AccessToken
    private func loadAccessToken(codeStr:String){
        NetworkTools.shareInstance.loadUserAccessToken(codeStr: codeStr) { (result, error) in
            //1.判断是否成功
            if error != nil {
                JLog(message: error.debugDescription)
                return
            }
            
            //2.请求成功
            //obj can be converted to JSON data
            if !JSONSerialization.isValidJSONObject(result as Any) {
                JLog(message: "无法解析出JSONString")
                return
            }
            
            //3.将字典转成模型对象
            let userAccount = UserAccount(dict: result as! [String : AnyObject])
            userAccount.saveAccount()
            
            //4.获取用户信息
            self.loadUserInfo(account: userAccount)
        }
    }
    
    //获取用户信息
    private func loadUserInfo(account:UserAccount){
        
        guard let accessToken = account.access_token else {
            return
        }
        guard let uid = account.uid else {
            return
        }
        
        NetworkTools.shareInstance.loadUserInfo(access_token: accessToken, uid: uid) { (result, error) in
            //1.判断是否成功
            if error != nil {
                JLog(message: error.debugDescription)
                return
            }
            
            //2.请求成功
            //obj can be converted to JSON data
            if !JSONSerialization.isValidJSONObject(result as Any) {
                JLog(message: "无法解析出JSONString")
                return
            }
            
            //3.解析成功
            guard let userInfoDict = result as? [String : AnyObject] else {
                return
            }
            
           account.avatar_large = userInfoDict["avatar_large"] as? String
           account.screen_name = userInfoDict["screen_name"] as? String
            
           //4.保存模型到本地
           account.saveAccount()
            
           //5.显示欢迎界面
           self.dismiss(animated: false, completion: {
                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
            })
        }
    }
    
}
